<template>
  <div class="user-table hei-1">
    <div class="search">
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
        style="display: flex; margin-top: 20px; margin-left: 8px"
      >
        <el-form-item label="人员姓名:" prop="name">
          <el-input
            v-model="form.name"
            size="small"
            clearable
            placeholder="人员姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="account">
          <el-input
            v-model="form.account"
            size="small"
            clearable
            placeholder="手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态:">
          <el-select
            v-model="form.state"
            size="small"
            placeholder="角色状态"
            clearable
          >
            <el-option label="启用" value="1"></el-option>
            <el-option label="停用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left: 30px">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchUser"
            size="small"
            >查阅</el-button
          >
          <el-button size="small" @click="resetForm('form')" style="width: 75px"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div style="display: flex">
      <el-button
        type="primary"
        style="margin-bottom: 10px; margin-left: 16px"
        size="small"
        icon="el-icon-plus"
        @click="dialogVisible = true"
        >新增</el-button
      >
      <el-button
        type="primary"
        style="margin-bottom: 10px; margin-left: 16px"
        size="small"
        icon="el-icon-delete"
        @click="submitSelectedData"
        >批量禁用</el-button
      >
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 98%; margin: 0 auto"
      size="large"
      table-layout="auto"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"> </el-table-column>
      <el-table-column prop="uid" label="Id" width="50"> </el-table-column>
      <el-table-column prop="account" label="登陆账号" width="120">
      </el-table-column>
      <el-table-column prop="password" label="密码" width="100">
      </el-table-column>
      <el-table-column prop="name" label="人员姓名" width="120">
      </el-table-column>
      <el-table-column prop="regTime" label="注册时间" width="120">
      </el-table-column>
      <el-table-column prop="lastLoginTime" label="上次登录时间" width="170">
      </el-table-column>
      <el-table-column prop="role" label="角色" width="110">
        <template slot-scope="scope">
          {{ scope.row.role === 2 ? "平台运营人员" : "养殖企业" }}
        </template>
      </el-table-column>
      <el-table-column prop="state" label="用户状态" width="100">
        <template slot-scope="scope">
          {{ scope.row.state === 1 ? "启用" : "停用" }}
        </template>
      </el-table-column>
      <el-table-column prop="operation" label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
            type="primary"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            v-if="scope.row.state === 1"
            @click="handleDelete(scope.$index, scope.row)"
            >禁用</el-button
          >
          <el-button
            size="mini"
            v-else
            type="success"
            @click="handleEnable(scope.$index, scope.row)"
            >启用</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handResetPwd(scope.row.uid, scope.row.account)"
            >密码重置</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="martop-1 marright-2">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[6, 10, 15]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <div>
      <el-dialog title="新增用户" :visible.sync="dialogVisible" width="30%">
        <el-form
          :label-position="labelPosition"
          label-width="80px"
          :model="formData"
        >
          <el-form-item label="手机号" class="wi-1">
            <el-input
              v-model="formData.account"
              clearable
              placeholder="手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="valuetype" style="float: left; width: 300px">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" style="margin-right: 40px"
            >取 消</el-button
          >
          <el-button type="primary" @click="handSubmit">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="修改用户" :visible.sync="dialogVisible1" width="30%">
        <el-form
          :label-position="labelPosition"
          label-width="80px"
          :model="formData"
        >
          <el-form-item label="Id" class="wi-1">
            <el-input v-model="formData.uid" readonly></el-input>
          </el-form-item>
          <el-form-item label="手机号" class="wi-1">
            <el-input v-model="formData.account" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-select
              v-model="formData.role"
              style="float: left; width: 300px"
            >
              <el-option label="养殖企业" value="1"></el-option>
              <el-option label="平台运营人员" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false" style="margin-right: 40px"
            >取 消</el-button
          >
          <el-button type="primary" @click="handEdit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import "@/assets/PublicLess.less"
export default {
  data () {
    return {
      tableData: [],
      currentPage: 1, // 当前页码
      total: 0, // 总条数
      pageSize: 6, // 每页的数据条数
      dialogVisible: false,
      dialogVisible1: false,
      labelPosition: 'right',
      formData: {
        uid: '',
        account: '',
        role: ''
      },
      options: [
        {
          value: '1',
          label: '养殖企业'
        },
        {
          value: '2',
          label: '平台运营人员'
        }
      ],
      valuetype: '1',
      form: {
        name: '',
        account: '',
        state: ''
      },
      selectedData: []
    }
  },
  methods: {
    handleEdit (index, row) {
      console.log(index, row)
      this.dialogVisible1 = true
      this.formData.uid = row.uid
      this.formData.account = row.account
      this.formData.role = String(row.role)
    },
    handleDelete (index, row) {
      console.log(index, row)
      this.$confirm('您确认要禁用该用户吗？', '禁用用户提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post('/api/users/del', { uid: row.uid }).then(res => {
          if (res.data.code == 1) {
            this.$message.success(res.data.msg)
          } else {
            this.$message.error(res.data.msg)
          }
          this.getUserList()
        })
      }).catch(() => {
        this.dialogVisible = false
      })
    },
    handleEnable (index, row) {
      this.$axios.post('/api/users/enable', { uid: row.uid }).then(res => {
        if (res.data.code == 1) {
          this.$message.success(res.data.msg)
        } else {
          this.$message.error(res.data.msg)
        }
        this.getUserList()
      })
    },
    handResetPwd (uid, account) {
      this.$confirm("您确认要重置该用户的密码吗?重置后的密码为手机号后六位", "重置密码确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const newPassword = account.substr(-6)
        const data = {
          uid: uid,
          password: newPassword
        }
        this.$axios.post('/api/users/resetPwd', data).then(res => {
          if (res.data.code == 1) {
            this.$message.success(res.data.msg)
            this.getUserList()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        this.dialogVisible = false
      })
    },
    handleSizeChange (page) {
      this.pageSize = page
      this.getUserList()
    },
    handleCurrentChange (page) {
      this.currentPage = page
      // 调用searchUser时传递false，避免显示成功消息
      this.searchUser(true, false)
    },
    getUserList () {
      const hasSearchConditions = this.form.account || this.form.name || this.form.state
      if (hasSearchConditions) {
        // 如果存在搜索条件，则调用搜索接口而不是全部数据的接口
        this.searchUser(true) // 添加参数以区分是否为分页调用
      } else {
        // 原有的获取所有用户列表的逻辑
        this.$axios.get('/api/users/list', {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize
          }
        }).then(res => {
          this.tableData = res.data.data
          this.total = res.data.total
        })
      }
    },
    handSubmit () {
      console.log(this.formData.account, this.valuetype)
      const data = {
        account: this.formData.account,
        role: parseInt(this.valuetype)
      }
      console.log(data)
      if (data.account === '') {
        this.$message.error("手机号不能为空!")
      } else {
        this.$axios.post('/api/users/add', data).then(res => {
          if (res.data.code === 1) {
            this.$message.success("添加成功!")
            this.dialogVisible = false
            this.getUserList()
          } else {
            this.$message.error("添加失败!")
          }
        })
      }
    },
    async handEdit () {
      console.log(this.formData)
      let res = await this.$axios.post('/api/users/edit', this.formData)
      if (res.data.code === 1) {
        this.$message.success(res.data.msg)
        this.dialogVisible1 = false
        this.getUserList()
      } else {
        this.$message.error(res.data.msg)
      }
    },
    searchUser (isPaging = false, showSuccessMessage = true) {
      const data = {
        page: {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        },
        user: {
          account: this.form.account,
          name: this.form.name,
          state: parseInt(this.form.state)
        }
      }
      this.$axios.post('/api/users/search', data).then(res => {
        if (res.data.code === 1) {
          this.tableData = res.data.data
          this.total = res.data.total
          // 根据showSuccessMessage参数决定是否显示成功消息
          if (showSuccessMessage) {
            this.$message.success(res.data.msg)
          }
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.form.state = ""
    },
    handleSelectionChange (selectedRows) {
      this.selectedData = selectedRows.map(row => row.uid)
    },
    submitSelectedData () {
      this.$confirm("您确认要批量禁用这些用户吗?", "批量禁用用户确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        console.log(this.selectedData)
        const data = [...this.selectedData]
        this.$axios.post('/api/users/delById', data).then(res => {
          if (res.data.code == 1) {
            this.$message.success(res.data.msg)
            this.getUserList()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        this.dialogVisible = false
      })
    }
  },
  created () {
    this.getUserList()
  },
  components: {
  },
}
</script>

<style lang="less" scoped>
.user-table {
  margin-top: 20px;
}

.search {
  display: flex;
}

.el-form-item {
  margin-right: 15px;
}
</style>